package com.leonzhangxf.server.service;

import com.leonzhangxf.server.register.ServerRegister;
import com.leonzhangxf.server.register.ZkServerRegister;
import com.leonzhangxf.service.IUserService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.context.ApplicationContext;
import sun.net.util.IPAddressUtil;
import sun.nio.ch.Net;

import java.net.InetSocketAddress;

/**
 * @author leonzhangxf
 */
public class ServerStarter {

    private static ServerRegister serverRegister;

    //创建一个方法启动服务器
    public static void startServer(int port, ApplicationContext applicationContext) throws Exception {
        //1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
            //设置通道为NIO
            .channel(NioServerSocketChannel.class)
            //创建监听channel
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                    //获取管道对象
                    ChannelPipeline pipeline = nioSocketChannel.pipeline();
                    //给管道对象pipeLine 设置编码
                    pipeline.addLast(new StringEncoder());
                    // pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                    //把我们自顶一个ChannelHander添加到通道中
                    UserServiceHandler userServiceHandler = new UserServiceHandler();
                    userServiceHandler.setApplicationContext(applicationContext);
                    pipeline.addLast(userServiceHandler);
                }
            });

        //4.绑定端口
        serverBootstrap.bind(port).sync();

        // 注册服务节点信息
        serverRegister = new ZkServerRegister("127.0.0.1:2181");
        serverRegister.register(IUserService.class.getName(), "127.0.0.1", port);
    }
}
